package com.sxhuayuan.parking.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.sxhuayuan.parking.config.Constant;
import com.sxhuayuan.parking.service.ExitingCarService;
import com.sxhuayuan.parking.service.RedisService;
import com.sxhuayuan.parking.service.impl.pojo.ExitingCar;

import lombok.extern.log4j.Log4j2;

/**
 * redis实现
 * 
 * @author gy
 */
@Log4j2
@Component("exitingCarRedisServiceImpl")
public class ExitingCarRedisServiceImpl implements ExitingCarService {

	@Autowired
	RedisService redisService;

	@Override
	public void put(String localChannelSn, ExitingCar car) {
		if (car != null) {
			String json = JSON.toJSONString(car);
			redisService.updateString(getKey(localChannelSn), json, Constant.PARK_FEE_CACHE_TTL);
		}
	}

	@Override
	public ExitingCar get(String localChannelSn) {
		String json = redisService.getString(getKey(localChannelSn));
		ExitingCar exitingCar = JSON.parseObject(json, ExitingCar.class);
		if (exitingCar != null && exitingCar.isExpired()) {
			log.debug("缓存已过期:{}", exitingCar.getCarPlate());
			return null;
		}
		return exitingCar;
	}

	@Override
	public boolean hasKey(String localChannelSn) {
		return get(localChannelSn) != null;
	}

	private String getKey(String localChannelSn) {
		return String.format("%s:%s", "exitingcar", localChannelSn);
	}

	@Override
	public boolean remove(String localChannelSn) {
		return redisService.removeString(getKey(localChannelSn));
	}
}
